package com.lanyou.esb.redis.proxy.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.lanyou.esb.common.Constants4Redis;
import com.lanyou.esb.redis.JedisPoolUtils;
import com.lanyou.esb.redis.proxy.base.BaseStrJedisProxy;
import com.lanyou.esb.redis.vo.IfAvgResTimesVo;

/**
 * 接口平均响应时间Redis操作代理
 * 
 * @author Davey.wu
 */
@Service
public class IfAvgResTimesJedisProxy extends BaseStrJedisProxy<IfAvgResTimesVo> {

	public IfAvgResTimesJedisProxy() {
		this.setTimeOut(Constants4Redis.REDIS_TIMEOUT_IFAVGRESTIME);
	}

	@Override
	public long setex(String key, IfAvgResTimesVo target)
			throws JsonProcessingException {
		String result = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			result = jedis.set(key, toJson(target));
			// 区间总响应时间增加
			jedis.incrByFloat(getNumKey(generateKeyFromObject(target)),
					target.getAvgResTimes());
			// 区间总请求次数增加
			jedis.incrBy(getTimesKey(generateKeyFromObject(target)), 1);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (StringUtils.isBlank(result)) {
			return 0l;
		}
		if (STRING_SET_RESULT.equalsIgnoreCase(result)) {
			return 1;
		}
		return 0;
	}

	@Override
	public String generateKeyFromObject(IfAvgResTimesVo target) {
		// TODO Auto-generated method stub
		return target.getIfId() + KEY_SEPARATOR + target.getSection();
	}

	/**
	 * 区间总响应时间
	 * 
	 * @param target
	 * @return
	 */
	public String getNumKey(String key) {
		return key + KEY_SEPARATOR + Constants4Redis.SUFFIX_NUMBER;
	}

	/**
	 * 区间总请求次数
	 * 
	 * @param target
	 * @return
	 */
	public String getTimesKey(String key) {
		return key + KEY_SEPARATOR + Constants4Redis.SUFFIX_TIMES;
	}

	public String get(Jedis jedis, String key) {
		return jedis.get(key);
	}

}
